<template>
  <div class="add">
    <h1 style="text-align:center;margin-top:10px">{{stuData.id?'修改':'新增'}}学生信息</h1>
    <Form :model="formItem" :label-width="80" class="form">
      <FormItem label="姓名">
        <Input v-model="formItem.name" placeholder="请输入姓名"/>
      </FormItem>
      <FormItem label="性别">
        <RadioGroup v-model="formItem.gender">
          <Radio label="男">男</Radio>
          <Radio label="女">女</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="年龄">
        <Input v-model="formItem.age" placeholder="请输入年龄"/>
      </FormItem>
      <FormItem label="爱好">
        <CheckboxGroup v-model="formItem.hobbies">
          <Checkbox label="吃饭"></Checkbox>
          <Checkbox label="睡觉"></Checkbox>
          <Checkbox label="打豆豆"></Checkbox>
          <Checkbox label="豆豆是谁"></Checkbox>
        </CheckboxGroup>
      </FormItem>
      <FormItem label="学历">
        <Select v-model="formItem.edu">
          <Option value="小学">小学</Option>
          <Option value="初中">初中</Option>
          <Option value="高中">高中</Option>
          <Option value="本科">本科</Option>
          <Option value="研究生及以上">研究生及以上</Option>
        </Select>
      </FormItem>
      <FormItem label="简介">
        <Input v-model="formItem.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}"/>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="saveFun">保存</Button>
        <Button type="error" style="margin-left: 8px" @click="clearFun">清空</Button>
        <Button type="warning" style="margin-left: 8px" @click="cancelFun">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import axios from "../axios";
import { stuUrl } from "../baseUrl/index";

export default {
  data() {
    return {
      formItem: {}
    };
  },
  props: ["stuData"],
  methods: {
    saveFun() {
      let data = JSON.parse(JSON.stringify(this.formItem));
      data.hobbies = data.hobbies.join("/");
      let url = stuUrl;
      let method = "post";
      if (this.formItem.id) {
        url = `${stuUrl}/${this.formItem.id}`;
        method = "put";
      }
      axios({
        url,
        method,
        data,
        success: data => {
          this.formItem = {};
          this.$router.push("/home");
        }
      });
    },
    clearFun() {
      this.formItem = {};
    },
    cancelFun() {
      this.$router.push("/home");
    }
  },
  mounted() {
    if (this.stuData.id) {
      this.stuData.hobbies = this.stuData.hobbies.split("/");
      this.formItem = this.stuData;
    }
  }
};
</script>

<style scoped>
.add {
  margin: 0 20px;
}
.form {
  margin-top: 20px;
}
</style>
